Page({
  data: {
    searchResults: []
  },

  onInput: function(e) {
    const keyword = e.detail.value;
    console.log('keyword',keyword);
    if (!keyword) {
      this.setData({ searchResults: [] });
      return;
    }
    this.getWeatherByCity(keyword)    
  },
  getWeatherByCity(cityName) {
    const that = this;
    const key = 'eb0c86513b134bd4a66b87e35b9f8f8a';
    
    wx.request({
      url: `https://nj6r6pwu2k.re.qweatherapi.com/geo/v2/city/lookup?location=${cityName}&key=${key}`,
      success(res) {
        console.log('res',res);
        const cityData = res.data.location;
        that.setData({ searchResults: cityData });
      },
      fail() {
        wx.showToast({
          title: '获取城市信息失败',
          icon: 'none'
        });
      }
    });
  },
  onSelectCity: function(e) {
    const index = e.currentTarget.dataset.id;
    const selectedCity = this.data.searchResults[index];
    
    wx.setStorageSync('currentCity', {
      name: selectedCity.name,
      adm1: selectedCity.adm1,
      adm2: selectedCity.adm2,
      lat: selectedCity.lat,
      lon: selectedCity.lon
    });
    
    wx.navigateBack();
  }
});